package kr.hkit.androidcomplete02.ch16;

import java.util.ArrayList;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class CheckQuestionFrg extends Activity implements CheckDialogFragment.NoticeDialogListener{
TextView tv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialogtest);
		tv = (TextView) findViewById(R.id.p_text);
		
	}
	
	public void mOnClick(View v){
		CheckDialogFragment listFrg = new CheckDialogFragment();
		listFrg.show(getFragmentManager(), "dialog");
	}

	public void onDialogClick(DialogFragment frg, String res) {
		tv.setText("선택한 과일은 : " + res);
	}
	
}

class CheckDialogFragment extends DialogFragment{
	NoticeDialogListener mListener;
	ArrayList<Integer> mSelects = new ArrayList<Integer>();
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		try{
		mListener = (NoticeDialogListener) activity;
		}catch(ClassCastException e){
			Log.d("ClassCastException", activity.toString() + "ListDialogFragment을 구현");
		}
		
	}
	
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment frg, String res);
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		return new AlertDialog.Builder(getActivity())
		.setTitle("음식을 선택하시오")
		.setIcon(R.drawable.ic_launcher)
		.setMultiChoiceItems(R.array.fruits, null, new OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				
				// 참인 경우
				if(isChecked){
					mSelects.add(which);
				} else if(mSelects.contains(which)){
					mSelects.remove(mSelects.indexOf(which));
				}
			}
		})
		.setPositiveButton("확인", new OnClickListener() {
			// onClick()에서 which는 누르는 버튼의 id값
			public void onClick(DialogInterface dialog, int which) {
				
				String[] fruits = getResources().getStringArray(R.array.fruits);
				StringBuilder sb = new StringBuilder();
				for(int idx : mSelects){
					sb.append(fruits[idx] + ", ");
				}
				sb.delete(sb.length()-2, sb.length()-1);
				mListener.onDialogClick(CheckDialogFragment.this, sb.toString());
			}
		})
		.setNegativeButton("취소", null)
		.create();
	}
}
